<?php
/**
 * 题库
 * User: cxm
 * Date: 2021/1/8
 * Time: 15:01
 */

namespace App\Http\Controllers\Admin\Question;
use App\Http\Controllers\Admin\Controller;
use App\Models\Question;
use App\Models\QuestionOptions;
use Carbon\Carbon;
use Carbon\Exceptions\Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class QuestionController extends Controller {
    /**
     * 题列表
     * URL POST:/admin/question/lists
     * @param Request $request
     * @param string keyword 关键字
     * @param int limit 每页显示条数
     * @param int page 页码
     * @return mixed
     */
    public function getLists(Request $request){
        $params = $request->only(['keyword','limit','page']);
        $keyword = isset($params['keyword']) ? $params['keyword'] : '';
        if (!empty($keyword)) {
            $params['where'][] = ['title','like','%'.$keyword.'%'];
        }
        // 选项
        $params['with'][] = 'options:question_id,option,content';
        // 排序
        $params['orderBy'] = ['sort asc','created_at desc'];
        $result = Question::listByWhere($params);
        return $this->success('查询成功',$result);
    }

    /**
     * 题添加、编辑
     * URL POST:/admin/question/store
     * @param Request $request
     * @param int id 编辑时必传
     * @param string title 题目
     * @param string answer 题答案
     * @param array options 选项信息 [['option'=>'A','content'=>'111111']]
     * @param int sort 排序
     * @return mixed
     */
    public function store(Request $request){
        $params = $request->only(['id','title','answer','options','sort']);
        $id = isset($params['id']) ? $params['id'] : 0;
        $validator = Validator::make($params,[
            'title'             => ['required'],
            'answer'            => ['required'],
            'options.*.option'  => ['required'],
            'options.*.content' => ['required']
        ],[
            'title.required'            => '题目是必须的',
            'answer.required'           => '答案是必须的',
            'options.*.option.required' => '题选项是必须的',
            'options.*.content.required'=> '题选项内容是必须的'
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        if ($id == 0) {
            $question = new Question();
        }else{
            $question = Question::find($id);
            if (!$question) {
                return $this->error('题不存在');
            }
        }
        DB::beginTransaction();
        try {
            $question->title            = $params['title'];
            $question->answer           = $params['answer'];
            $question->sort             = $params['sort'];
            if ($question->save()) {
                if ($params['options']) {
                    // 删除之前的题选项
                    QuestionOptions::where('question_id',$question->id)->forceDelete();
                    $data = [];
                    foreach ($params['options'] as $key=>$item) {
                        $data[] = [
                            'question_id'       => $question->id,
                            'option'            => $item['option'],
                            'content'           => $item['content'],
                            'sort'              => $key+1,
                            'created_at'        => Carbon::now()
                        ];
                    }
                    QuestionOptions::insert($data);
                }
            }
            DB::commit();
        }catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }
        return $this->success('操作成功');
    }

    /**
     * 题删除
     * URL POST:/admin/question/delete
     * @param Request $request
     * @param array ids 题ID [1,2,3……]
     * @return mixed
     */
    public function delete(Request $request){
        $params = $request->only(['ids']);
        if (!array_key_exists('ids',$params) || empty($params['ids'])) {
            return $this->error('请选择需要删除的题');
        }
        DB::beginTransaction();
        // 删除题选项
        $options = QuestionOptions::whereIn('question_id',$params['ids'])->delete();
        if ($options === false) {
            DB::rollBack();
            return $this->error('题选项删除失败');
        }
        // 删除题
        $question = Question::whereIn('id',$params['ids'])->delete();
        if ($question ===  false) {
            DB::rollBack();
            return $this->error('题删除失败');
        }
        DB::commit();
        return $this->success('操作成功');
    }

    /**
     * 排序
     * URL POST:/admin/question/updateSort
     * @param Request $request
     * @param int id 题ID
     * @param int sort 排序值
     * @return mixed
     */
    public function updateSort(Request $request){
        $params = $request->only(['id','sort']);
        $validator = Validator::make($params,[
            'id'            => ['required'],
            'sort'          => ['required']
        ],[
            'id.required'   => '请选择题',
            'sort.required' => '请输入排序值'
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        // 查看题是否存在
        $question = Question::find($params['id']);
        if (!$question) {
            return $this->error('题不存在');
        }
        $where = [];
        $where[] = ['id',$params['id']];
        $field = ['sort'=>$params['sort']];
        $result = Question::modify($where,$field);
        if ($result === false) {
            return $this->error('操作失败');
        }
        return $this->success('操作成功');
    }

    /**
     * 是否显示
     * URL POST:/admin/question/updateStatus
     * @param Request $request
     * @param int id 题ID
     * @return mixed
     */
    public function updateStatus(Request $request){
        $params = $request->only(['id']);
        if (!array_key_exists('id',$params) || empty($params['id'])) {
            return $this->error('缺少题ID');
        }
        $trader = Question::find($params['id']);
        if (!$trader) {
            return $this->error('文章不存在');
        }
        $status = $trader->status == 1 ? 2 : 1;
        $where = [];
        $where[] = ['id',$params['id']];
        $field = ['status'=>$status];
        $res = Question::modify($where,$field);
        if ($res === false) {
            return $this->error('修改失败');
        }
        return $this->success('修改成功');
    }


}